import json
import tkinter.font as tf
from datetime import datetime
import tkinter as tk
import requests
import xlwt

# 0.获取实时时间
def get_time():
    # 转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
    # 1.获取当前日期和时间
    now = datetime.now()
    # 2.格式化日期为"YYYY-MM-DD"
    today_str = now.strftime('%Y-%m-%d')
    # 打印结果
    # print(today_str)
    return today_str
# 清除内容
def clear_text_widget():
    # 清除内容
    text_widget.delete("1.0", "end")

# 1.爬取开奖数据
def get_history_datas():
    # pz为下载的数据个数
    if entry_widget.get():
        pz = entry_widget.get()
    else:
        pz = '100'
    # print(pz)
    # 中福利彩票官网
    url = f'http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&pageNo=1&pageSize={pz}&systemType=PC'
    headers = {
        'Host': 'www.cwl.gov.cn',
        'Referer': 'http://www.cwl.gov.cn/c/2023/01/17/527544.shtml',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; root64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
    }
    response = requests.get(url=url, headers=headers)
    result = json.loads(response.text).get('result')
    # print(result)
    data_dict = {}
    for res in result:
        data_dict[res['code']] = res['red'] + "," + res['blue']
    # print(data_dict)
    return data_dict

# 2.保存ex数据
def savedatas_to_ex():
    clear_text_widget()
    data_dict = get_history_datas()
    today = get_time()
    # Excel路径
    excel_path = f'{today}历史数据.xls'
    # 创建新的工作簿
    wb = xlwt.Workbook()
    # 创建新的工作表
    she = wb.add_sheet("彩票")
    al = xlwt.Alignment()
    # 设置水平居中
    al.horz = 0x02
    # 设置垂直居中
    al.vert = 0x01

    # 添加边框
    borders = xlwt.Borders()
    # DASHED:虚线  NO_LINE:没有  THIN:实线
    borders.left = xlwt.Borders.THIN
    borders.right = xlwt.Borders.THIN
    borders.top = xlwt.Borders.THIN
    borders.bottom = xlwt.Borders.THIN
    borders.left_colour = 0x40
    borders.right_colour = 0x40
    borders.top_colour = 0x40
    borders.bottom_colour = 0x40

    # 设置背景颜色
    pattern = xlwt.Pattern()
    pattern.pattern = xlwt.Pattern.SOLID_PATTERN
    # 背景颜色
    pattern.pattern_fore_colour = 27

    # 黑色字体并居中
    # 初始化样式
    style0 = xlwt.XFStyle()
    style0.alignment = al
    # 为样式创建字体
    font0 = xlwt.Font()
    # 黑体
    font0.bold = True
    # 0：黑色；2：红色；12：蓝色
    font0.colour_index = 0
    # 设定样式
    style0.font = font0
    style0.borders = borders
    style0.pattern = pattern

    # 红色加粗字体并居中
    style01 = xlwt.XFStyle()
    style01.alignment = al
    font01 = xlwt.Font()
    font01.bold = True
    font01.colour_index = 2
    style01.font = font01
    style01.borders = borders
    style01.pattern = pattern

    # 蓝色加粗字体并居中
    style02 = xlwt.XFStyle()
    style02.alignment = al
    font02 = xlwt.Font()
    font02.bold = True
    font02.colour_index = 12
    style02.font = font02
    style02.borders = borders
    style02.pattern = pattern

    # 蓝色非加粗字体并居中
    style = xlwt.XFStyle()
    style.alignment = al
    font = xlwt.Font()
    # font.bold = True
    font.colour_index = 12
    style.font = font
    style.borders = borders

    # 红色非加粗字体并居中
    # 设置字体在单元格的位置
    alignment = xlwt.Alignment()
    # 水平方向
    alignment.horz = xlwt.Alignment.HORZ_CENTER
    # 竖直方向
    alignment.vert = xlwt.Alignment.VERT_CENTER
    style1 = xlwt.XFStyle()
    style1.alignment = alignment
    font1 = xlwt.Font()
    # font1.bold = True
    font1.colour_index = 2
    style1.font = font1
    style1.borders = borders

    # 第一行第一列写入数据
    she.write(0, 0, "期数\\彩票", style0)

    # 写入红色球数据
    for i in range(1, 34):
        she.write(0, i, i, style01)
    # 写入蓝色球数据
    for j in range(1, 17):
        she.write(0, j + 33, j, style02)

    # 设置列宽
    for k in range(1, 50):
        she.col(k).width = 256 * 3

    i = 1
    for key, value in data_dict.items():
        # 将字典中的键放在第0列
        she.write(i, 0, key, style0)
        values = value.split(",")
        red_list = values[0:-1]
        lan = int(values[-1])
        for hong in red_list:
            hong = int(hong)
            # 写入数据
            she.write(i, hong, hong, style1)
        she.write(i, lan + 33, lan, style)
        i += 1
    wb.save(excel_path)
    text_widget.insert('insert', "数据已保存: " + excel_path + "\n")

# 3.打印历史双色球数据，第2024033期：06 10 11 18 20 32 05
def print_history_datas():
    data_dict = get_history_datas()
    clear_text_widget()
    # print(data_dict)
    str_result = ""
    # 遍历，格式化文本数据
    for key, value in data_dict.items():
        ball = " ".join(value.split(","))
        str_result += "第" + key + "期：" + ball + "\n"

    font1 = tf.Font(family='楷体', size=18)
    text_widget.insert('insert', str_result + "\n")
    for i in range(1, str_result.count("第") + 1):
        text_widget.tag_add("tag1", "{}.1".format(i), "{}.8".format(i))
        text_widget.tag_add("tag2", "{}.10".format(i), "{}.28".format(i))
        text_widget.tag_add("tag3", "{}.28".format(i), "{}.30".format(i))
        text_widget.tag_config("tag1", foreground="green")
        text_widget.tag_config("tag2", foreground="red")
        text_widget.tag_config("tag3", foreground="blue")
        text_widget.config(font=font1)

# 4.数据统计分析
def analysis_datas():
    # 清空text
    clear_text_widget()
    data_dict = get_history_datas()
    # print(data_dict)
    red_list = []
    blue_list = []
    # 1.遍历历史数据，把所有红篮球放到一块
    for key, value in data_dict.items():
        red_ball = value.split(",")[:-1]
        red_list.extend(red_ball)
        # hong = ",".join(value.split(",")[:-1])
        blue_ball = value.split(",")[-1]
        blue_list.append(blue_ball)
    # print(red_list)
    # print(blue_list)

    # 2.list.count统计红蓝球次数，并构造新的字典数据
    red_dict = {}
    blue_dict = {}
    for i in range(1, 34):
        i = str(i).zfill(2)
        red_dict[i] = red_list.count(i)

    for i in range(1, 17):
        i = str(i).zfill(2)
        blue_dict[i] = blue_list.count(i)

    # 3.红球+蓝球，根据出现次数高低，进行降序排序
    red_dict = sorted(red_dict.items(), key=lambda x: x[1], reverse=True)
    blue_dict = sorted(blue_dict.items(), key=lambda x: x[1], reverse=True)
    # print(red_dict, blue_dict)
    # pz为下载的数据个数
    if entry_widget.get():
        pz = entry_widget.get()
    else:
        pz = '100'
    red_ball_result = f'近{pz}期红色球解析结果(倒序)：\n'
    blue_ball_result = f'近{pz}期蓝色球解析结果(倒序)：\n'
    # 打印红球出现的次数
    for k, v in red_dict:
        red_ball_result += k + " 出现次数：" + str(v) + "\n"
    # 打印蓝球出现的次数
    for k, v in blue_dict:
        blue_ball_result += k + " 出现次数：" + str(v) + "\n"

    result = red_ball_result + blue_ball_result

    text_lens = len(result.split("\n")[0])
    # print(result.split("\n"))
    font1 = tf.Font(family='楷体', size=18)
    text_widget.insert('insert', result + "\n")
    text_widget.tag_add("tag1", "1.0", "1.{}".format(text_lens))
    text_widget.tag_add("tag2", "35.0", "35.{}".format(text_lens))
    for i in range(2, 35):
        text_widget.tag_add("tag3", "{}.0".format(i), "{}.2".format(i))
        text_widget.tag_add("tag4", "{}.8".format(i), "{}.14".format(i))
    for i in range(36, 52):
        text_widget.tag_add("tag5", "{}.0".format(i), "{}.2".format(i))
        text_widget.tag_add("tag6", "{}.8".format(i), "{}.14".format(i))
    text_widget.tag_config("tag1", foreground="red")
    text_widget.tag_config("tag2", foreground="blue")
    text_widget.tag_config("tag3", foreground="red")
    text_widget.tag_config("tag4", foreground="green")
    text_widget.tag_config("tag5", foreground="blue")
    text_widget.tag_config("tag6", foreground="green")
    text_widget.config(font=font1)

# 5.主函数
if __name__ == '__main__':
    root = tk.Tk()
    root.title('福彩双色球————分析工具')
    root.geometry('600x560')
    # 1.输入框
    entry_var = tk.StringVar()
    # fleur:十字箭头 heart:心形 man:男人 plus:十字架 mouse:鼠标
    entry_widget = tk.Entry(root, width=22, bg='yellow', bd=3, cursor='heart', textvariable=entry_var, validate="focusout")
    entry_widget.grid(row=0, column=0, sticky='NW', padx=78, pady=5)
    tk.Label(root, text='历史期数(期):').grid(row=0, sticky='W')
    tk.Label(root, text="注：只可填入数字,填10表示前10期数据,不填默认为100").grid(row=0, padx=180, pady=5)

    # 2.新建文本框
    text_widget = tk.Text(root)
    text_widget.grid(row=2, column=0, sticky="W", padx=5, pady=18)
    # 3.功能按钮
    xz_button = tk.Button(root, text='下载数据', width=8, command=print_history_datas)
    xz_button.grid(row=1, column=0, sticky="W", padx=5, pady=5)
    ex_button = tk.Button(root, text='生成Excel文件', width=12, command=savedatas_to_ex)
    ex_button.grid(row=1, column=0, sticky="W", padx=80, pady=5)
    jx_button = tk.Button(root, text="解析数据", command=analysis_datas)
    jx_button.grid(row=1, column=0, sticky="W", padx=186, pady=5)
    qk_button = tk.Button(root, text="清空内容", command=clear_text_widget)
    qk_button.grid(row=1, column=0, sticky="W", padx=256, pady=5)
    tk.Label(root, text="注：生成Excel文件更易观察").grid(row=1, padx=318, pady=5)
    root.mainloop()
